/*
 * @Author: 'zhangkeqq' '2211709169@qq.com'
 * @Date: 2025-08-02 10:28:08
 * @LastEditors: 'zhangkeqq' '2211709169@qq.com'
 * @LastEditTime: 2025-08-04 21:36:48
 * @FilePath: \vue3-admin-node\vue3-admin\src\store\modules\menu.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import {
  defineStore
} from 'pinia'
import router from '@/router'
import {ref,toRaw} from "vue";

// 引入深拷贝方法
import cloneDeep from 'lodash/cloneDeep'
// 引入路由
import {constantRoute,asyncRoute,anyRoute} from '@/router/routes'
import {returnMenuList} from '@/api/login/index'
//用于过滤当前用户需要展示的异步路由


// 辅助函数：递归收集目标路由数组中所有的name
function collectRouteNames(routes: any[]): Set<string> {
    const names = new Set<string>();
    function traverse(routeList: any[]) {
        routeList.forEach(route => {
            if (route.name) {
                names.add(route.name);
            }
            if (route.children && route.children.length > 0) {
                traverse(route.children);
            }
        });
    }
    traverse(routes);
    return names;
}
// 递归筛选路由，只保留name匹配的元素，完全使用asyncRoute的格式
function filterRoutes(routes: any[], targetNames: Set<string>): any[] {
    // 不修改原始数组，创建新数组
    return routes
        .filter(route => route.name && targetNames.has(route.name))
        .map(route => {
            // 直接使用asyncRoute中的路由对象结构，不混合其他数组的属性
            const resultRoute = { ...route };
            // 递归处理子路由
            if (resultRoute.children && resultRoute.children.length > 0) {
                resultRoute.children = filterRoutes(resultRoute.children, targetNames);
            }
            return resultRoute;
        });
}

// 主函数：从asyncRoute中筛选出与userAdminRouter name相同的元素，保留asyncRoute的格式
function filterAsyncRoute(asyncRoute: any[], userRoutes: any[]): any[] {
    // 收集用户路由中所有的name
    const userRouteNames = collectRouteNames(userRoutes);
    // 从asyncRoute中筛选，完全保留asyncRoute的格式
    return filterRoutes(asyncRoute, userRouteNames);
}

//使用了setup写法
export const useMenu = defineStore('menuInfo',{
    state:()=>{
        return{
            menuList:constantRoute as any,
            list:constantRoute as any,
        }
    },
    actions:{
        async getMenu(){
            let id = localStorage.getItem('id')
            const res = await returnMenuList(id)
            const userAsyncRoute = filterAsyncRoute(cloneDeep(asyncRoute),res.data)
            console.log('userAsyncRoute',userAsyncRoute)
            //带children
            let start:any = []
            //不带children
            let end:any = []

            userAsyncRoute.filter((item:any)=>{
                if(item.children && item.children.length > 0){
                    start.push(item)
                }else{
                    end.push(item)
                }
            })
            this.list.forEach((item:any)=>{
                if(item.name == 'menu'){
                    item.children.push(...end)
                }
            })
            let myList = toRaw(this.list)
            this.menuList = [...myList,...start,...anyRoute]
            //目前路由器管理只有常量路由，计算完毕后异步路由和人力路由需要动态添加
            const newRoutes = [...myList,...start,...anyRoute]
            newRoutes.forEach((route:any)=>{
                router.addRoute(route)
            })
        }
    },
    persist:true
})